//
//  CameraVC.m
//  GCWSDKDemo
//
//  Created by 陈超 on 2016/12/29.
//  Copyright © 2016年 陈超. All rights reserved.
//

#import "CameraVC.h"
#import "TitlesSettingVC.h"

//第一步:SDK包的导入
#import "CameraRecorder.h"
#import "AudioManager.h"
#import "VideoEffectUtil.h"
#import "VideoPlayBackVC.h"
#import "BorderModel.h"

#import "MBProgressHUDManager.h"
//======================
@interface CameraVC ()<RecordFinshedDelegate,UIActionSheetDelegate,AVAudioPlayerDelegate,TitlesSetingDelegate>
@property (strong, nonatomic) CameraRecorder           *cameraRecorder;//录制编码
@property (weak, nonatomic) IBOutlet UIView *preView;
@property (strong, nonatomic) NSMutableArray *borders;//录制编码

@property (weak, nonatomic) IBOutlet UIButton *captureButton;
@property (weak, nonatomic) IBOutlet UISwitch *flashSwitch;
@property (weak, nonatomic) IBOutlet UISlider *brightNessSlider;
@property(copy,nonatomic)NSURL *outPutVideoUrl;
@property (weak, nonatomic) IBOutlet UIButton *uploadButton;
@property(nonatomic,assign)BOOL recordingCanceld;
@end

@implementation CameraVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self initData];
    [self initView];
}
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    self.navigationController.navigationBar.hidden=YES;
    //第三步:准备好伴奏音乐
    [[AudioManager manager] createAudioPlayerFromUrl:self.mp3Url delegate:self];
    [self.cameraRecorder startAnimation];
   
}
-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    self.navigationController.navigationBar.hidden=NO;
    [self.cameraRecorder stopAnimation];
    [[AudioManager manager] clear];
}
-(void)initData{
    
    NSArray *array=@[@"空白",@"安宁(静)",@"世外桃源(静)",@"爱情(动)"];
    self.borders=@[].mutableCopy;
    __weak typeof (self)weakSelf=self;
    //生成可选择的遮罩
    [array enumerateObjectsUsingBlock:^(NSString * obj, NSUInteger idx, BOOL * _Nonnull stop) {
        BorderModel *borderModel=[BorderModel new];
        borderModel.name=obj;
        if(idx==0){
            borderModel.borderLocalUrl=[[NSBundle mainBundle] URLForResource:obj withExtension:@"png"];
            borderModel.type=BorderTypeBlank;
        }else if(idx==3){
            borderModel.borderLocalUrl=[[NSBundle mainBundle] bundleURL];
            borderModel.type=BorderTypeDynamic;
        }else {
            borderModel.borderLocalUrl=[[NSBundle mainBundle] URLForResource:obj withExtension:@"png"];
            borderModel.type=BorderTypeStatic;
        }
        [weakSelf.borders addObject:borderModel];
    }];
}
-(void)initView{
    //第二步:初始化摄像头
    self.cameraRecorder=[[CameraRecorder alloc] initWithParams:self.preView delegate:self userDeniedAuthorizationBlock:^{
        NSLog(@"请允许访问相机");
    }];

    [self.flashSwitch setOn:self.cameraRecorder.isFlashOn];
    //8.0以下系统不支持加亮
    if([[UIDevice currentDevice].systemVersion floatValue]<8.0){
        [self.brightNessSlider setHidden:YES];
    }else {
        [self.brightNessSlider setMaximumValue:self.cameraRecorder.getMaxBrightNess];
        [self.brightNessSlider setMinimumValue:self.cameraRecorder.getMinBrightNess];
        //亮度建议初始化为中间值，否则在极值的时候自动调整功能不敏感感
        [self.cameraRecorder changeBrightNess:(self.cameraRecorder.getMinBrightNess+self.cameraRecorder.getMaxBrightNess)];
        [self.brightNessSlider setValue:self.cameraRecorder.getBrightNess];
    }
}

-(BOOL)shouldAutorotate{
    return YES;
}
#pragma mark - RecordFinshedDelegate
-(void)RecordFinshed:(NSURL *)outPutVideoUrl error:(NSError*)error{
    self.outPutVideoUrl=outPutVideoUrl;
    if(self.recordingCanceld){//取消拍摄，准备重拍
        [[AudioManager manager] clear];
      [[AudioManager manager] createAudioPlayerFromUrl:self.mp3Url delegate:self];
    }else {
        [self onClickTitlesSettingButton:nil];
    }
}
#pragma mark - AVAudioPlayerDelegate
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
    //音乐播放完了就停止拍摄
    [self.cameraRecorder stopRecord];
}
#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if(buttonIndex>0){
        BorderModel *borderModel=self.borders[buttonIndex-1];
        //选择并应用遮罩
        self.cameraRecorder.borderModel=borderModel;
        [self.cameraRecorder updateBorder];
    }
}
#pragma mark - TitlesSetingDelegate
-(void)captruedTitlesView:(UIView *)view{
    
   }
#pragma mark - UI交互方法
- (IBAction)onClickStartCaptureButton:(UIButton *)sender {
    
    if(!self.cameraRecorder.isCapturing){
        //开始拍摄
        [self.cameraRecorder startRecord];
        [[AudioManager manager] play];
           [sender setTitle:@"停止拍摄" forState:UIControlStateNormal];
        
    }else {
        //结束拍摄
        [[AudioManager manager] stop];
        [self.cameraRecorder stopRecord];
        self.captureButton.enabled=NO;
           [sender setTitle:@"开始拍摄" forState:UIControlStateNormal];
    }
}
- (IBAction)onClickBackButon:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];

}
//上传前压缩方法
- (IBAction)onClickUploadButton:(UIButton *)sender {
    //要压缩的视频路径
//    NSURL *inputVideoUrl=[VideoEffectUtil sharedInstance].outPutVideoUrl;
    //压缩后存放的路径
//    [VideoEffectUtil sharedInstance].outPutVideoUrl=    [VideoEffectUtil sharedInstance].outPutVideoUrl=[NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:@"compressed.mp4"]];
//
//    [[VideoEffectUtil sharedInstance] compressVideo:inputVideoUrl progressBlock:^(float prog) {
//        
//        NSLog(@"progress: %f",prog);
//        dispatch_async(dispatch_get_main_queue(), ^{
//            //注意在主线程更新UI
//           
//            
//        });
//    } completeBlock:^(NSURL *videoUrl) {
//         NSLog(@"url: %@",[videoUrl path]);
//     
//        
//    } failureBlock:^(NSError *error) {
//                NSLog(@"error: %@",error);
//        
//    }];
}

//选择遮罩
- (IBAction)onClickSelectBorderButton:(id)sender {
    UIActionSheet *actionSheet=[[UIActionSheet alloc] initWithTitle:@"选择遮罩" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:nil];
    [self.borders enumerateObjectsUsingBlock:^(BorderModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [actionSheet addButtonWithTitle:obj.name];
    }];
    [actionSheet showInView:self.view];
}
//亮度调节
- (IBAction)onAdjustBrightness:(UISlider *)sender {
    [self.cameraRecorder changeBrightNess:sender.value];
}
//拉瘦
- (IBAction)onEnhanceHight:(UISlider *)sender {
    NSLog(@"sender.value %f",sender.value);
    self.cameraRecorder.tranformModel.scaleY=1+(sender.value/2);
    [self.cameraRecorder changeTransform];
}
//分身
- (IBAction)onClickMutiPart:(UISegmentedControl *)sender {
    self.cameraRecorder.tranformModel.partsNum=sender.selectedSegmentIndex+1;
    [self.cameraRecorder resetPreViewToPartNum];
}
//设置片头
- (IBAction)onClickTitlesSettingButton:(UIButton *)sender {
    TitlesSettingVC *titlesSettingVC=[TitlesSettingVC new];
    titlesSettingVC.delegate=self;
    titlesSettingVC.borderModel=self.cameraRecorder.borderModel;
    titlesSettingVC.mp3Url=self.mp3Url;
    titlesSettingVC.inputUrl=self.outPutVideoUrl;
    titlesSettingVC.tranformModel=self.cameraRecorder.tranformModel;
    [self.navigationController pushViewController:titlesSettingVC animated:YES];
}
//闪光灯
- (IBAction)onSwitchFlash:(UISwitch *)sender {
    [self.cameraRecorder setFlashEnable:sender.isOn];
}
//切换摄像头
- (IBAction)onClickSwitchCamera:(UIButton *)sender {
    [self.cameraRecorder switchCamera];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
